package com.nf.health.app.homepage.activity;

import android.app.AlertDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;

import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.adapter.ViewHolder;
import com.nf.health.app.models.MyDoctor;
import com.nf.health.app.utils.DensityUtil;
import com.nf.health.app.utils.ImageLoaderUtils;
import com.nf.health.app.utils.KeyBoardManager;
import com.nf.health.app.utils.ScreentUtils;
import com.nf.health.app.utils.ViewUtil;

import java.util.List;

/**
 * 中医体检——输入卡密码，支付，指定医生
 * @author fei
 *
 */
public class DoctorSelectedActivity extends BaseActivity {

	protected static final String TAG = DoctorSelectedActivity.class.getSimpleName();
	private String major_id;
	private List<MyDoctor> doctors;
	private int currentPos = -1;
	private AlertDialog alertDialog;
	private EditText et_pwd;
	private String hospitalid;
	private int block = 4;//一块字符串的长度
	private int startIndex = block-1;//一块字符串的长度
	private int screenWidth;
	private int margin;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		major_id = getIntent().getStringExtra("majorid");
		hospitalid = getIntent().getStringExtra("hospitalid");
		screenWidth = ScreentUtils.getScreenWidth(this);
		margin = DensityUtil.dip2px(this, 20);

		setTitleBar(R.layout.titlebar_base);
		ViewUtil.setText(this, R.id.titlebar_title_tv, "指定医生");

		setContent(R.layout.activity_doctor_selected);

		initView();

		if(hospitalid != null){
			//直接加载医生列表
			initDoctor(hospitalid);
		}
	}

	private void initView() {
		et_pwd = ViewUtil.getView(this, R.id.et_pwd);
		Button btn_commit = ViewUtil.getView(this, R.id.btn_commit);

		btn_commit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				KeyBoardManager.closeKeyboard(DoctorSelectedActivity.this, et_pwd);
				String password =et_pwd.getText().toString();
				if(TextUtils.isEmpty(password)){
					showToast("密码不能为空");
					return;
				}
				String pwd = password.replaceAll(" ","");
				if(pwd.length()==20){
					provider.requestPay(pwd,major_id,"pay");
				}else{
					showToast("请输入正确的20位密码");
				}
			}
		});
		et_pwd.addTextChangedListener(new TextWatcher() {


			int beforeTextLength = 0;  
			int onTextLength = 0;  
			boolean isChanged = false;  

			int location = 0;// 记录光标的位置  
			private char[] tempChar;  
			private StringBuffer buffer = new StringBuffer();  
			int konggeNumberB = 0;  

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				onTextLength = s.length();  
				buffer.append(s.toString());  
				if (onTextLength == beforeTextLength || onTextLength <= 3 || isChanged) {  
					isChanged = false;  
					return;  
				}  
				isChanged = true;  

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				beforeTextLength = s.length();  
				if (buffer.length() > 0) {  
					buffer.delete(0, buffer.length());  
				}  
				konggeNumberB = 0;  
				for (int i = 0; i < s.length(); i++) {  
					if (s.charAt(i) == ' ') {  
						konggeNumberB++;  
					}  
				}  
			}

			@Override
			public void afterTextChanged(Editable s) {

				if (isChanged) {  
					location = et_pwd.getSelectionEnd();  
					int index = 0;  
					while (index < buffer.length()) {  
						if (buffer.charAt(index) == ' ') {  
							buffer.deleteCharAt(index);  
						} else {  
							index++;  
						}  
					}  

					index = 0;  
					int konggeNumberC = 0;  
					while (index < buffer.length()) {  
						if ( index % 5 == 4 ) {  
							buffer.insert(index, ' ');  
							konggeNumberC++;  
						}  
						index++;  
					}  

					if (konggeNumberC > konggeNumberB) {  
						location += (konggeNumberC - konggeNumberB);  
					}  

					tempChar = new char[buffer.length()];  
					buffer.getChars(0, buffer.length(), tempChar, 0);  
					String str = buffer.toString();  
					if (location > str.length()) {  
						location = str.length();  
					} else if (location < 0) {  
						location = 0;  
					}  

					et_pwd.setText(str);  
					Editable etable = et_pwd.getText();  
					Selection.setSelection(etable, location);  
					isChanged = false;  

				}
			}
		});
	}
	@SuppressWarnings("unchecked")
	@Override
	public void handleActionSuccess(String actionName, Object object) {
		if("pay".equals(actionName)){
			//支付成功
			String hospitalid = (String)object;
			initDoctor(hospitalid);
		}else if("query".equals(actionName)){
			doctors = (List<MyDoctor>)object;
			provider.requestAddScore("8","");//添加积分
//			showToast("评估订单提交成功");
			showDialog();
		}else if("update".equals(actionName)){
			//订单和医生绑定成功
			alertDialog.dismiss();
			showToast("已为评估订单指定医生");
			setResult(RESULT_OK);//DetectionHistoryListActivity  需要
			finish();
		}
	}

	/**
	 * 获取医生列表
	 * @param hospitalid
	 */
	private void initDoctor(String hospitalid) {
		provider.requestQueryDoctor(hospitalid,"query");		
	}

	private void showDialog() {
		final AlertDialog.Builder build = new AlertDialog.Builder(this);
		alertDialog = build.create();
		alertDialog.show();//必须在设置View之前调用
		alertDialog.setCanceledOnTouchOutside(false);
		View view = View.inflate(this, R.layout.dialog_doc_list, null);
		LayoutParams params = new LinearLayout.LayoutParams(screenWidth-margin*2, LayoutParams.WRAP_CONTENT);
		params.setMargins(margin, 0, margin, 0);
		view.setLayoutParams(params);
		alertDialog.setContentView(view);

		Button btn_submit = (Button) alertDialog.findViewById(R.id.btn_submit);
		ListView listview = (ListView) alertDialog.findViewById(R.id.listview);
		final MyDoctorAdapter myDoctorAdapter = new MyDoctorAdapter();
		listview.setAdapter(myDoctorAdapter);
		btn_submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(currentPos == -1){
					showToast("请指定体验医生");
					return;
				}
				provider.requestUpdateMajorevaDoctor(major_id, doctors.get(currentPos).getDoctorid(), "update");
			}
		});
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				currentPos = position;
				myDoctorAdapter.notifyDataSetChanged();
			}
		});
	}
	
	class MyDoctorAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			return doctors==null?0:doctors.size();
		}

		@Override
		public Object getItem(int position) {
			return doctors.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = ViewHolder.get(parent, convertView,R.layout.item_doc_selected, position);
			ImageView iv_user_head_icon = holder.getView(R.id.iv_user_head_icon);
			ImageLoaderUtils.getinstance(DoctorSelectedActivity.this).getImage(iv_user_head_icon,doctors.get(position).getHimg(), R.drawable.moren_doctor_image);
			CheckBox cb_selected = holder.getView(R.id.cb_selected);
			holder.setText(R.id.doctor_name, doctors.get(position).getNick());
			holder.setText(R.id.doctor_type, doctors.get(position).getProfessional());
			holder.setText(R.id.doctor_speciality_details, doctors.get(position).getHospitalname());
			if(position == currentPos){
				cb_selected.setChecked(true);
			}else{
				cb_selected.setChecked(false);
			}
			return holder.getConvertView();
		}

	}
}
